<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use anlutro\LaravelSettings\Facade AS Setting;

class SettingController extends Controller
{
    public function index()
    {
        return $this->returnJSON([
            'org_type' => $this->str2array(Setting::get('org_type', "NGO组织;大学生团体;企业;学校;政府街道")),
            'project_type' => $this->str2array(Setting::get('project_type', "赛会服务;应急救援;城市运行;文化教育;关爱服务;社区服务;绿色环保;医疗卫生;在线志愿服务;国际服务;京外服务;其他")),
            'service_target' => $this->str2array(Setting::get('service_target', "儿童;青少年;孤寡老⼈;残障⼈⼠;优抚对象;特困群体;其他")),
            'team_type' => $this->str2array(Setting::get('team_type', "党政机关;教育事业单位;卫生事业单位;科技事业单位;文化事业单位;社会福利利事业单位;其他事业单位;群团组织;居委会或村委会;国有企业;民营企业;社会团体;社会服务机构;基金会")),
            'volunteer_security' => $this->str2array(Setting::get('volunteer_security', "志愿者保险;集中乘车;交通补贴;餐饮或食物;提供饮水;提供住宿;志愿者服装;志愿服务工具;免费体检;专项培训;志愿服务证书;其他")),
        ]);
    }

    public function show($id) {
        return $this->returnJSON([
            "options" => $this->str2options(Setting::get($id, ""))
        ]);
    }

    public function store(Request $request) {
        if ($request->has("org_type")) {
            $org_type = $this->array2str($request->get("org_type"));
            Setting::set('org_type', $org_type);
        }

        if ($request->has("project_type")) {
            $org_type = $this->array2str($request->get("project_type"));
            Setting::set('project_type', $org_type);
        }

        if ($request->has("service_target")) {
            $org_type = $this->array2str($request->get("service_target"));
            Setting::set('service_target', $org_type);
        }

        if ($request->has("team_type")) {
            $org_type = $this->array2str($request->get("team_type"));
            Setting::set('team_type', $org_type);
        }

        if ($request->has("volunteer_security")) {
            $org_type = $this->array2str($request->get("volunteer_security"));
            Setting::set('volunteer_security', $org_type);
        }


        Setting::save();
        return $this->returnJSON(null);
    }

    protected function str2options($str) {
        if (!isset($str) || empty($str)) {
            return [];
        }

        return array_map(function($item) {
            return [
                'label' => $item,
                'value' => $item,
            ];
        }, explode(";", $str));
    }

    protected function str2array($str) {
        if (!isset($str) || empty($str)) {
            return [];
        }

        return array_map(function($item) {
            return [
                'name' => $item
            ];
        }, explode(";", $str));
    }

    protected function array2str($arr) {
        if (!isset($arr) || !is_array($arr)) {
            return "";
        }

        return join(";", array_map(function ($item) {
            return $item['name'];
        }, $arr));
    }
}
